'use strict';

const createConfig = require('uni-config-center');

const uidConfig = createConfig({
	pluginId: 'uni-id'
});

const db = uniCloud.database();
const dbcmd = db.command;
const wxmpapi_token_id = 'usemall-wxmpapi-token';

const utils = require('../utils');

// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
module.exports = {
	appid: uidConfig.config('mp-weixin.oauth.weixin.appid'),
	// access_token 获取小程序全局后台接口调用凭据，有效期最长为7200s，2个小时
	token: '',
	token_expired: 0,
	
	// 获取 access_token
	get_token: async function(valid = false) {
		let res = await db.collection('usemall-token').doc(wxmpapi_token_id).get();
		const [usemallToken] = res.data;
		if (usemallToken && usemallToken._id && usemallToken.token_expired > Date.now()) {
			if (valid && !await this.valid_token(usemallToken.token)) {
				console.log('valid_token 已失效重新获取');
				await db.collection('usemall-token').doc(wxmpapi_token_id).update({
					token_expired: 0
				});
				return await this.get_token();
			}
			
			this.token = usemallToken.token;
			this.token_expired = usemallToken.token_expired;
			return this.token;
		}
		
		const appid = uidConfig.config('mp-weixin.oauth.weixin.appid');
		const appsecret = uidConfig.config('mp-weixin.oauth.weixin.appsecret');
		
		let url = `https://api.weixin.qq.com/cgi-bin/stable_token`;
		
		res = await utils.http.post(url, {
			grant_type: "client_credential",
			appid: appid,
			secret: appsecret
		});
		
		console.log('token res', res, typeof res);
		
		if (res && res.errcode) {
			console.log('wxmpapi-token 响应' + res.errmsg);
			throw new Error('wxmpapi-token 响应' + res.errmsg);
		}
		
		if (res && res.access_token) {
			this.token = res.access_token;
			this.token_expired = Date.now() + ((res.expires_in - 5 * 60) * 1000);
			
			console.log('get_token', this.token, this.token_expired);
		}
		
		// 写入最新 token 数据
		await db.collection('usemall-token').doc(wxmpapi_token_id).set({
			token: this.token,
			token_expired: this.token_expired,
			res: res,
			req: {},
			type: 'wxmpapi'
		});
		
		return this.token;
	},
	// 验证 access_token
	valid_token: async function(token) {
		const url = 'https://api.weixin.qq.com/wxaapi/log/get_client_version?access_token=' + token;
		
		const res = await utils.http.get(url);
		
		return res.errcode === 0;
	},
	// 快递公司列表
	get_delivery: async function(valid = false) {
		const token = await this.get_token(valid);
		const url = 'https://api.weixin.qq.com/cgi-bin/express/business/delivery/getall?access_token=' + token;
		
		const res = await utils.http.get(url);
		
		return res;
	},
	// 发货
	upload_shipping_info: async function(data, valid = false) {
		const token = await this.get_token(valid);
		const url = 'https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=' + token;
		
		const res = await utils.http.post(url, data);
		
		return res;
	},
	// 创建二维码	https://developers.weixin.qq.com/doc/offiaccount/Account_Management/Generating_a_Parametric_QR_Code.html
	// 	临时二维码 QR_SCENE、QR_STR_SCENE
	// 	永久二维码 QR_LIMIT_SCENE、QR_LIMIT_STR_SCENE
	qrcode_create: async function(data, valid = false) {
		
		// access_token
		const token = await this.get_token(valid);
		const url = `https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=${token}`;
		
		// 发送请求
		const res = await utils.http.post(url, data);
		console.log('utils.http.post res', res);
		
		if (res.errcode) {
			if (res.errcode == 40001) {
				// 令牌失效
				return await this.qrcode_create(data, true);
			}
			
			throw new Error(`wxapi-qrcode_create 创建失败 ${res.errmsg}`);
		}
		
		// 二维码图片地址
		res.qrcode = `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${res.ticket}`;
		
		return res;
	},
	// 创建临时二维码
	qrcode_create_temp: async function(value, expire_seconds = 86400) {
		const data = {
			// 二维码有效时间，以秒为单位。 最大不超过2592000（即30天）
			expire_seconds: expire_seconds,
			action_name: '', 
			action_info: {
				scene: {}
			}
		};
		
		if (typeof value === 'number') {
			// QR_SCENE为临时的整型参数值
			data.action_name = 'QR_SCENE';
			// 场景值ID，临时二维码时为32位非0整型
			data.action_info.scene.scene_id = value;
		} else {
			// QR_STR_SCENE为临时的字符串参数值
			data.action_name = 'QR_STR_SCENE';
			// 场景值ID（字符串形式的ID），字符串类型，长度限制为1到64
			data.action_info.scene.scene_str = value;
		}
		
		return await this.qrcode_create(data);
	},
	// 创建永久二维码
	qrcode_create_limit: async function(value) {
		const data = {
			action_name: '', 
			action_info: {
				scene: {}
			}
		};
		
		if (typeof value === 'number') {
			// QR_LIMIT_SCENE为永久的整型参数值
			data.action_name = 'QR_LIMIT_SCENE';
			// 场景值ID，临时二维码时为32位非0整型
			data.action_info.scene.scene_id = value;
		} else {
			// QR_LIMIT_STR_SCENE为永久的字符串参数值
			data.action_name = 'QR_LIMIT_STR_SCENE';
			// 场景值ID（字符串形式的ID），字符串类型，长度限制为1到64
			data.action_info.scene.scene_str = value;
		}
		
		return await this.qrcode_create(data);
	}
	
}
